#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：python_learning 
@File ：socket_sender_with_GUI_copilot.py
@IDE  ：PyCharm 
@Author ：李涵彬
@Date ：2024/3/1 17:04 
"""

import socket
import tkinter as tk
from tkinter import messagebox
from typing import Optional


class SocketClient:
    def __init__(self, host: str, port: int):
        """
        初始化SocketClient类
        :param host: ip地址
        :param port: 端口号
        """
        self.host = host
        self.port = port

    def send_message(self, message: str):
        """
        发送报文
        :param message: 报文内容
        """
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.connect((self.host, self.port))
            s.sendall(message.encode())


class App:
    def __init__(self, root: tk.Tk):
        """
        初始化App类
        :param root: tkinter的root窗口
        """

        self.root = root
        self.root.title("Socket Message Sender")

        # 创建IP地址输入框
        self.host_label = tk.Label(root, text="Target IP Address:")
        self.host_label.grid(row=0, column=0, padx=5, pady=5)
        self.host_entry = tk.Entry(root)
        self.host_entry.grid(row=0, column=1, padx=5, pady=5)

        # 创建端口号输入框
        self.port_label = tk.Label(root, text="Target Port:")
        self.port_label.grid(row=1, column=0, padx=5, pady=5)
        self.port_entry = tk.Entry(root)
        self.port_entry.grid(row=1, column=1, padx=5, pady=5)

        # 创建报文内容输入框
        self.message_label = tk.Label(root, text="Message:")
        self.message_label.grid(row=2, column=0, padx=5, pady=5)
        self.message_entry = tk.Entry(root)
        self.message_entry.grid(row=2, column=1, padx=5, pady=5)

        # 创建发送报文按钮
        self.send_button = tk.Button(
            root, text="Send Message", command=self.send_message
        )
        self.send_button.grid(row=3, column=0, columnspan=2, padx=5, pady=5)

        # 设置默认值
        self.default_values()

        # # 第二套布局
        # self.root = root
        # self.root.title("Socket Message Sender")
        #
        # # 创建并显示host标签和输入框
        # self.host_label = tk.Label(root, text="Host:")
        # self.host_label.pack()
        # self.host_entry = tk.Entry(root)
        # self.host_entry.pack()
        #
        # # 创建并显示port标签和输入框
        # self.port_label = tk.Label(root, text="Port:")
        # self.port_label.pack()
        # self.port_entry = tk.Entry(root)
        # self.port_entry.pack()
        #
        # # 创建并显示message标签和输入框
        # self.message_label = tk.Label(root, text="Message:")
        # self.message_label.pack()
        # self.message_entry = tk.Entry(root)
        # self.message_entry.pack()
        #
        # # 创建并显示发送报文按钮
        # self.send_button = tk.Button(
        #     root, text="Send Message", command=self.send_message
        # )
        # self.send_button.pack()

    def default_values(self):
        """
        设置默认值
        """
        # 默认IP为本机IP
        self.host_entry.insert(0, "127.0.0.1")

        # 默认端口为8888
        self.port_entry.insert(0, "8888")

        # 默认报文内容为"test"
        self.message_entry.insert(0, "test")

    def send_message(
        self,
        host: Optional[str] = "127.0.0.1",
        port: Optional[int] = 8888,
        message: Optional[str] = "test",
    ):
        """
        获取输入框中的ip地址、端口号和报文内容，然后发送报文
        :param host: ip地址，默认为'127.0.0.1'
        :param port: 端口号，默认为8888
        :param message: 报文内容，默认为'test'
        """
        host = self.host_entry.get() or host
        port = int(self.port_entry.get() or port)
        message = self.message_entry.get() or message

        try:
            client = SocketClient(host, port)
            client.send_message(message)
            messagebox.showinfo("Success", "Message sent successfully!")
        except Exception as e:
            messagebox.showerror("Error", str(e))


root = tk.Tk()
app = App(root)
root.mainloop()
